<template>
  <div class="codeContanier">
    <div v-code>
      <pre class="codepre"><code :class="codeClassName" class="codeBlock">{{ codeBlock }}</code></pre>
    </div>
    <span class="copytext" @click="copyClick">复制代码</span>
    <textarea ref="textAreaRef" style="position: fixed; top: 10000px; left: 10000px; opacity: 0"></textarea>
  </div>
</template>

<script>
import { js_beautify, css_beautify, html_beautify } from 'js-beautify'
import hljs from "highlight.js";
import("highlight.js/styles/atom-one-dark.css");
import { Message } from "element-ui";
import { computed, ref } from "vue";
export default {
  directives: {
    code: {
      inserted(el) {
        el.querySelectorAll("pre code").forEach((codeEl) => {
          hljs.highlightElement(codeEl);
        });
      },
    },
  },
  props: {
    code: {
      type: String,
      default: `<button>
                       <slot></slot>
</button>`,
    },
    lang: {
      type: String,
      default: "html",
    },
    format: {
      type: Boolean,
      default: true
    }
  },
  setup(props) {
    const codeBlock = computed(() => {
      if (!props.format) return props.code
      let beautFunc = html_beautify
      if (props.lang === 'javascript') {
        beautFunc = js_beautify
      } else if (props.lang === 'css') {
        beautFunc = css_beautify
      }
      return beautFunc(
        props.code,
        {
          indent_size: 2,
          space_in_empty_paren: true,
          "wrap_line_length": "85",
        }
      )
    })
    const textAreaRef = ref(null);
    const codeClassName = computed(() => `language-${props.lang}`);
    const copyClick = () => {
      try {
        textAreaRef.value.value = codeBlock.value;
        textAreaRef.value.select();
        document.execCommand("copy");
        Message({
          type: "success",
          message: "复制成功",
        });
      } catch (error) {
        console.log(error);
        Message({
          type: "error",
          message: "复制失败",
        });
      }
    };
    return {
      copyClick,
      codeClassName,
      codeBlock,
      textAreaRef,
    };
  },
};
</script>
<style scoped lang="less">
.codeContanier {
  position: relative;

  .codepre {
    margin: 0;
    padding: 0;
    font-size: 0.16rem;
    line-height: 1.5;

    .codeBlock {
      padding-top: 0.3rem !important;
      padding-bottom: 0.3rem !important;
    }
  }

  .copytext {
    position: absolute;
    right: 0.3rem;
    font-size: 0.14rem;
    top: 0.1rem;
    color: #abb2bf;
    cursor: pointer;

    &:hover {
      color: #fff;
    }
  }
}
</style>
